import { _decorator, AudioClip, AudioSource, Collider2D, Component, Contact2DType, instantiate, IPhysics2DContact, Node, Prefab, RigidBody2D, v2, Vec2 } from 'cc';
import { Brick } from './Brick';
import { Slider } from './Slider';
const { ccclass, property } = _decorator;

@ccclass('Ball')
export class Ball extends Component {

    @property(Prefab)
    private ball:Prefab = null

    
    @property(AudioClip)
    clip:AudioClip = null

    private rigidBody:RigidBody2D =null
    private maxSpeed:number = 30
    private lv
    start() {
        let collider = this.node.getComponent(Collider2D)
        this.rigidBody = this.node.getComponent(RigidBody2D)
        collider.on(Contact2DType.BEGIN_CONTACT,this.onBeginContact,this)
        this.lv = this.rigidBody.linearVelocity
    }

    firstBall(v2:Vec2){
        this.rigidBody.linearVelocity = v2
    }

    // 球数*3
    ballMultiplyThree(){
        let ballPre = instantiate(this.ball)
        this.node.getParent().addChild(ballPre)
        ballPre.setPosition(this.node.position)
        ballPre.getComponent(RigidBody2D).linearVelocity = new Vec2((this.lv.x*Math.cos(10*Math.PI/180))-(this.lv.y*Math.sin(10*Math.PI/180)),(this.lv.x*Math.sin(10*Math.PI/180))+(this.lv.y*Math.cos(10*Math.PI/180)))
        ballPre = instantiate(this.ball)
        this.node.getParent().addChild(ballPre)
        ballPre.setPosition(this.node.position)
        ballPre.getComponent(RigidBody2D).linearVelocity = new Vec2((this.lv.x*Math.cos(350*Math.PI/180))-(this.lv.y*Math.sin(350*Math.PI/180)),(this.lv.x*Math.sin(350*Math.PI/180))+(this.lv.y*Math.cos(350*Math.PI/180)))
    }
    

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null){
        if(otherCollider.node.getComponent(Brick)){
            otherCollider.node.getComponent(Brick).die()
        }
        if(otherCollider.node.name == 'Slider'){
            this.lv.x = this.lv.x+otherCollider.node.getComponent(RigidBody2D).linearVelocity.x
            if(this.lv.x > (this.maxSpeed-2) ){
                this.lv.x = (this.maxSpeed-2)
            }else if(this.lv.x < -(this.maxSpeed-2)){
                this.lv.x = -(this.maxSpeed-2)
            }
            this.lv.y = Math.sqrt(this.maxSpeed*this.maxSpeed-(this.lv.x*this.lv.x))
            this.rigidBody.linearVelocity = this.lv
        }
        if(this.rigidBody.linearVelocity != v2(0,0)){
            this.node.getComponent(AudioSource).playOneShot(this.clip)
        }
    }

    

    update(deltaTime: number) {
        if(this.node.getParent().getComponent(Slider).ballMultiplyThree == 1){
            this.ballMultiplyThree()
        }
        if(this.node.position.y<-1200){
            this.node.destroy()
        }
        this.lv = this.rigidBody.linearVelocity
    }
}


